package main

import (
	"database/sql"
	"fmt"
	"github.com/go-sql-driver/mysql"
	"log"
	"os"
)
var db * sql.DB

func main() {
	cfg := mysql.Config{
		User: os.Getenv("root"),
		Passwd: os.Getenv("root"),
		Net: "tcp",
		Addr: "localhost:3306",
		DBName : "test",

	}
	fmt.Println(cfg)
	db, err := sql.Open("mysql", "root:root@(127.0.0.1:3306)/test")
	if(err) != nil{
		fmt.Println("数据库连接失败")
	}else {
		fmt.Println("数据库连接成功")
		fmt.Println(db)
	}


	result, err := db.Query("select * from tb_test_user where id = ?", 1)
	if result != nil {
		log.Default().Printf("查询结果为", &result)
		var id,name string
		var age int
		for result.Next(){
			result.Scan(&id,&name,&age)
			fmt.Println(id,name,age)
		}
	}else {
		fmt.Println(err)
		fmt.Println("error")
	}
	result , err = db.Query("insert into tb_test_user(name,age)values (?,?)", "赵六", 20)
	log.Default().Printf("返回结果为",result)
	db.Close()
	/*var err error
	db, err = sql.Open("mysql",cfg.FormatDSN())
	if err != nil {
		log.Fatal(err)
	}

	pingErr := db.Ping()
	if pingErr != nil {
		log.Fatal(pingErr)
	}
	fmt.Println("Connected!")*/
}